package engine;

import java.io.File;
import java.io.IOException;

import javax.swing.JOptionPane;

/**
 * This class provides folder browsing and platform-specific file launching capabilities.
 * @author Shahriar Haque
 *
 */
public class Lemming {
	
	/**
	 * Returns a list of files in the directory given as the argument.
	 * @param path Absolute path name of a directory
	 * @return If path is valid directory, returns the file listing, null otherwise
	 */
	public static File[] explore(String path){
		
		File f = new File(path);
		
		if(!f.exists()) return null;
		if(!f.isDirectory()) return null;
		
		return f.listFiles();
	}
	
	/**
	 * Extracts the directory name of the given path
	 * @param path
	 * @return
	 */
	public static String getDirectoryName(String path){
		File f = new File(path);
		if(!f.isDirectory()) return null;
		
		return f.getName();
	}
	
	/**
	 * Runs the file specified by the given absolute path with its default application.
	 * Current version only supports Windows through:
	 * cmd /c filename.ext
	 * On a *Nix platform, this should be replaced by gnome-open filename.ext
	 * On the MacOS, the equivalent is open filename.ext
	 * @param path The full path of the file
	 */
	public static void run(String path){
		path = "\"" + path + "\"";
		
		try {
			Runtime.getRuntime().exec("cmd /c " + path);
		} 
		
		catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Sorry, couldn't launch the file!", "Error", JOptionPane.ERROR_MESSAGE);
		}
		
		
	}

	/**
	 * Returns a tidy representation of the size.
	 * @param size The size of a file in bytes
	 * @return
	 */
	public static String getFileSizeString(long size){
		String s = "";
		
		double kb = size/1024.0;
		kb = kb*100.0;
		kb = ((int)kb)/100.0;
		
		
		double mb = size/(1024.0*1024.0);
		mb = mb*100.0;
		mb = ((int)mb)/100.0;

		
		double gb = size/(1024.0*1024.0*1024.0);
		gb = gb*100.0;
		gb = ((int)gb)/100.0;
		
		if(gb >= 1) s = Double.toString(gb) + " gb";
		else if(mb >= 1) s = Double.toString(mb) + " mb";
		else if(kb >= 1) s = Double.toString(kb) + " kb";
		else s = size + " bytes";	
		
		
		
		
		return s;
	}
	
}
